package com.huawei.mytestapp.slice;

import com.danikula.videocache.CacheListener;
import com.danikula.videocache.HttpProxyCacheServer;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.Surface;
import ohos.agp.graphics.SurfaceOps;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.Point;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.audio.AudioManager;
import ohos.media.codec.Codec;
import ohos.media.codec.TrackInfo;
import ohos.media.common.Format;
import ohos.media.common.Source;
import ohos.media.player.Player;
import ohos.media.recorder.Recorder;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.logging.Logger;


public class MainAbilityIm extends AbilitySlice implements SurfaceOps.Callback {


    //需要一个正确的URL
    public static final String URL = "https://1251316161.vod2.myqcloud.com/5f6ddb64vodsh1251316161/6950eead5285890812637029535/iUn2HnRCGxMA.mp4";
    private String localUrl;
    private Player player;
    private HttpProxyCacheServer mCacheServerProxy=null;
    private Slider slider;
    SurfaceProvider surfaceProvider;

    //rewindTo​(long microseconds)

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
//        mCacheServerProxy = BaseApplication.getProxy(this);
        if (mCacheServerProxy == null) {
            Context context = this;
            mCacheServerProxy = new HttpProxyCacheServer(context);
        } else {

        }
        slider = new Slider(this);
        initView();
        initMediaPlayer();
        playee();
    }

    private void initView() {
        // 步骤 1 声明布局
        DirectionalLayout directionLayout= new DirectionalLayout(this);
        // 步骤 2 设置布局大小
        directionLayout.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
        directionLayout.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);
        // 步骤 3 设置布局属性及 ID（ID 视需要设置即可）
        directionLayout.setOrientation(Component.VERTICAL);
        directionLayout.setPadding(32, 32, 32, 32);


        Text text= new Text(this);
        text.setText("视频播放……");
        text.setTextSize(50);
        text.setId(13);
        // 步骤 4.1 为控件添加对应布局的布局属性
        DirectionalLayout.LayoutConfig layoutConfig = new
                DirectionalLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_CONTENT,
                ComponentContainer.LayoutConfig.MATCH_CONTENT);
        layoutConfig.alignment = LayoutAlignment.HORIZONTAL_CENTER;
        text.setLayoutConfig(layoutConfig);
        // 步骤 4.2 将 Text 添加到布局中
        directionLayout.addComponent(text);


        // 类似的添加一个 Button
        Button button = new Button(this);
//        layoutConfig.topMargin = 50;
        layoutConfig.setMargins(0, 50,0,0);
        button.setLayoutConfig(layoutConfig);
        button.setText("播放");
        button.setTextSize(50);
        button.setId(12);
        ShapeElement background = new ShapeElement();
        background.setRgbColor(new RgbColor(0xFF51A8DD));
        background.setCornerRadius(25);
        button.setBackground(background);
        button.setPadding(10, 10, 10, 10);
        button.setClickedListener(new Component.ClickedListener() {
            @Override
            // 在控件中增加对点击事件的监听
            public void onClick(Component Component) {
                // 按钮被点击
                // 按钮被按下后，需要执行的操作
                player.play();

            }
        });
        directionLayout.addComponent(button);


        surfaceProvider = new SurfaceProvider(this);

        surfaceProvider.setPadding(10, 80, 10 , 80);
        surfaceProvider.setHeight(540);
        surfaceProvider.setWidth(960);

        surfaceProvider.getSurfaceOps().get().addCallback(this);
        surfaceProvider.pinToZTop(true);
        directionLayout.addComponent(surfaceProvider);

//        surfaceProvider.setRotation(180);
        slider.setWidth(960);
        directionLayout.addComponent(slider);
        slider.setValueChangedListener(new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int i, boolean b) {
                long l =  player.getDuration() * i/100;
                player.rewindTo(l*1000);
//                HiLog.info(new HiLogLabel(3,0,"wuwuwu"),"hello");
            }

            @Override
            public void onTouchStart(Slider slider) {
            }

            @Override
            public void onTouchEnd(Slider slider) {
//
            }
        });

        // 步骤 5 将布局作为根布局添加到视图树中
        super.setUIContent(directionLayout);
    }


    private void initMediaPlayer() {
        player = new Player(this);

        player.setPlayerCallback(new Player.IPlayerCallback() {
            @Override
            public void onPrepared() {}
            @Override
            public void onMessage(int i, int i1) {}
            @Override
            public void onError(int i, int i1) {}
            @Override
            public void onResolutionChanged(int i, int i1) {}
            @Override
            public void onPlayBackComplete() {}
            @Override
            public void onRewindToComplete() {}
            @Override
            public void onBufferingChange(int i) {}
            @Override
            public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {}
            @Override
            public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {}
        });
    }


    private void playee() {

        mCacheServerProxy.registerCacheListener(mCacheListener,URL);
        localUrl = mCacheServerProxy.getProxyUrl(URL);
        //log
        Source source=new Source(localUrl);
//            source.setRecorderVideoSource(Recorder.VideoSource.SURFACE);
        player.setSource(source);


        player.prepare();
        player.play();


        String sharedFileName = sharedFileName(this);

    }

    public static String sharedFileName(Context context){
        File distDir = context.getDistributedDir();
        String filePath = distDir+File.separator+"note.data";
        return filePath;
    }

    //缓存相关
    private CacheListener mCacheListener = new CacheListener() {

        @Override
        public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
            HiLog.info(new HiLogLabel(3,0,"cache"),"Saving……,percent:"+String.valueOf(percentsAvailable));
            if (percentsAvailable == 100 && !cacheFile.getPath().endsWith(".download")) {
                HiLog.info(new HiLogLabel(3,0,"cache"),"Download already!");
            }
        }
    };


    @Override
    public void surfaceCreated(SurfaceOps surfaceOps) {

        player.setSurfaceOps(surfaceProvider.getSurfaceOps().get());
        player.prepare();
    }
    @Override
    public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) {
    }
    @Override
    public void surfaceDestroyed(SurfaceOps surfaceOps) {

    }
}
